package com.zhanglijie.theory.future.crawl;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.EOFException;
import java.net.URL;
import java.util.Arrays;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/8/16 0016 19:39
 */
public class ContentImpl implements Content{
    private byte[] content;
    public ContentImpl(String url){
        try {
            URL urlStr = new URL(url);
            DataInputStream dataInputStream = new DataInputStream(urlStr.openStream());
            byte[] bytes = new byte[1];
            int index = 0;
            try {
                while (true) {
                    int i = dataInputStream.readUnsignedByte();
                    if (bytes.length <= index) {
                        byte[] largeBuffer = new byte[bytes.length * 2];
                        System.arraycopy(bytes, 0, largeBuffer, 0, index);
                        bytes = largeBuffer;
                    }
                    bytes[index++] = (byte) i;

                }
            }catch (EOFException e){

            }finally {
                dataInputStream.close();
            }
            content = new byte[index];
            System.arraycopy(bytes,0,content,0,index);


        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    public byte[] getContent() {
        return content;
    }
}
